package cn.gz.lbs.jobs;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
 
import org.quartz.StatefulJob;

import com.netnewera.l1.ans.Ans;
import com.netnewera.l1.ans.Lia;
import com.netnewera.l1.ans.Posinfo;
import com.netnewera.l1.report.Ltrr;
import com.netnewera.l1.report.Posinfos;
import com.netnewera.l1.report.Report;
import com.netnewera.l1.req.Req;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;

import cn.gz.lbs.entity.CmsUser;
import cn.gz.lbs.entity.LirNeedEntity;
import cn.gz.lbs.entity.TLbsHistory;
import cn.gz.lbs.glsc.GLSCProxy;
import cn.gz.zoomtech.common.db.DbHandle;


public class LtrrJob implements StatefulJob {
	private static final Log log = LogFactory.getLog(LtrrJob.class);
	private LirNeedEntity entity;
 
	



	/**
	 * 
	* package_name: cn.gz.lbs.jobs
	* file_name:    LtrrJob.java
	* description: 周期定位转变成单次定位定时任务，以及负责返回给SP定位周期报告
	* 2013-8-30下午1:11:15
	* Author: chenhui
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	
	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {

		 long tranc_time_startOne = System.currentTimeMillis();
		 String tel = null;
		 Posinfo onePosInfo = null;
		 try {
			 Date reqTime = new Date();
			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = null;
		    String respStr = "defaultLtrrError";
			String respHead = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE ANS SYSTEM \"LOCANS.DTD\">";
			XStream xStream = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
			
			Scheduler scheduler  = context.getScheduler();
			String triggerName =  context.getTrigger().getName();
			this.entity = (LirNeedEntity) context.getJobDetail().getJobDataMap().get("entity");
			log.info("triggerName:"+triggerName+",LTAreqEntity:"+entity+",schedulerName:"+scheduler.getSchedulerName());
            tel = entity.getMsid();
//          step0:构建默认返回的定位报告
			Report report = this.createDefaultLtrrResp();
//	        step1:发单次请求,并将结果转换为设置到report需要的参数中
			try{
				GLSCProxy glscP = new GLSCProxy();
				Ans ans = glscP.reqToGLSCFromLtrrJob(entity);//				
				log.info("ltrrAnsFromProxy:"+ans);
//				设置参数
				List<Posinfo> posinfos = ans.getLia().getPosinfos();
				onePosInfo = posinfos.get(0);
				report.getLtrr().getPosinfo().setPosinfo(onePosInfo);
				report.getLtrr().setResult(ans.getLia().getResult());
				respStr = respHead+xStream.toXML(report);
				log.info("respReportStrIs:"+respStr);
			}catch(Exception e1){
				log.error("whenAccessGLSCError:"+entity.getReqId(),e1);
			}
//			step2:向Sp发送定位报告
			try{
				log.info("spReportUrl:"+entity.getSpReportUrl());
				httppost = new HttpPost(entity.getSpReportUrl());
				StringEntity myEntity = new StringEntity(respStr, "utf-8");
				httppost.addHeader("Content-Type", "text/xml");
				httppost.setEntity(myEntity);
			    httpclient.execute(httppost);
			    Thread.sleep(200);
			    httpclient.getConnectionManager().shutdown();
			    log.info("reportReqId:"+entity.getReqId()+"reportToSpOK.");
			}catch(Exception e2){
				log.error("respReportToSpError:"+entity.getReqId(),e2);
			}	
			
//			step3:写定位历史记录
			try{
//				step3-3-4:将定位结果写入历史表
				short respForm = 0;
				String reqType = "LTR";
				String respMemo = "";
				CmsUser cmsUser = entity.getCmsUser();
				long tranc_time_endOne = System.currentTimeMillis();
				int tranc_timesOne = (int) (tranc_time_endOne-tranc_time_startOne); //处理时间
				    
				    TLbsHistory history = new TLbsHistory();
				    history.setUserId(cmsUser.getId());
        		   
        		    
				    history.setMdn(tel);
				    history.setJindu(onePosInfo.getLongitude());
				    history.setWeidu(onePosInfo.getLatitude());
				    history.setOrid(entity.getOrid());
				    history.setRespCode(report.getLtrr().getResult());
				    
				    if("1".equals(onePosInfo.getPositionresult())||"2".equals(onePosInfo.getPositionresult())
				    	||"3".equals(onePosInfo.getPositionresult())	){
				    	history.setRespResult((byte)0);
				    	respMemo = "定位成功";
				    }else{
				    	history.setRespResult((byte)1);
				    	respMemo = "please watch POSITIONRESULT in Docfile";
				    }
				    history.setServerCode(entity.getServiceid());
				    history.setRespForm(respForm);
				    
				    history.setReqTime(reqTime);
				    
				    history.setTrancTimes(tranc_timesOne);
				    history.setRespMemo(respMemo);
				    history.setReqType(reqType);
				    
        			int saveResult = saveLbsHistory(history);
        			log.info("tel:"+tel+",saveHistory:"+saveResult);
			}catch(Exception e3){
				log.error("ltrrToTbError:",e3);
			}
		} catch (Exception ex) {
			log.error("LtrrJobError:",ex);
		}
	}
	


	/**
	 * 
	* package_name: cn.gz.lbs.jobs
	* file_name:    LtrrJob.java
	* description: 构建默认的包含Ltrr周期定位报告的Report
	* 2013-8-30下午5:02:14
	* Author: chenhui
	 * @param oneEntity
	 * @return
	 */
	private Report  createDefaultLtrrResp(){
		
		Report report = null;
		try{
//			构建report
			report = new Report();
			report.setLcsclientid(entity.getLcsclientid());
			report.setOrid(entity.getOrid());
			
//			构建ltrr对象。
			Ltrr ltrr = new Ltrr();
			ltrr.setReqId(entity.getReqId()+"");
			ltrr.setResult("1"); // 0：成功；其他值看文档，1：故障
			ltrr.setPrTrigger("1");
			ltrr.setTimeRemaining(""); // 这个值，暂时不设置，根据调试情况再做修改

			Posinfos posinfos = new Posinfos();
			
			Posinfo pos = new Posinfo();
			pos.setMsid(entity.getMsid());
			pos.setMsidtype(entity.getMsidType());
			pos.setPositionresult("1"); // 1:返回的初始位置
			
			posinfos.setPosinfo(pos);
			
			ltrr.setPosinfo(posinfos);
			 
			report.setLtrr(ltrr);
			
		}catch(Exception ex){
			report = null;
			ex.printStackTrace();
			log.warn("createDefaultLtrrRespError:",ex);
		}
		
		log.info("defaultLtrrResp:"+report);
		return report;
		
	}
	
	/**
	 * 
	* package_name: cn.gz.lbs.main
	* file_name:    SPRequestManager.java
	* description: 调用数据库操作类，写定位记录到定位历史表
	* 2013-7-9下午3:56:19
	* Author: chenhui
	 * @param entity
	 * @return
	 */
	private int saveLbsHistory(TLbsHistory entity){
		int savaResult = 99;
		try{
			DbHandle dbh = new DbHandle();
			savaResult= dbh.saveLbsHistory(entity);

		}catch(Exception ex){
			log.error("errorWhenCallSaveHistory:",ex);
		}
		return savaResult;
	}
 

}
